﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.Entity;
using HdipCricketClub.Models;
using HdipCricketClub.ViewModels;

namespace HdipCricketClub.ViewModels
{
    public class SelectedTeamCreatedViewModel
    {
        // properties

        public Fixture SelectedFixture { get; set; }

        public List<ClubFixturePlayer> TeamCreated { get; set; }

        // database context

        CricketClubEntities db = new CricketClubEntities();

        // repositories

        FixtureRepository fixtureRepository = new FixtureRepository();

        // methods

        public SelectedTeamCreatedViewModel ParseFormCollection(FormCollection formCollection)
        {
            string[] fixtureId = formCollection.GetValues("SelectedFixture.fixture_id");
            string[] playerId = formCollection.GetValues("item.player_id");
            string[] contact = formCollection.GetValues("item.contact");
            string[] confirmed = formCollection.GetValues("item.confirmed");

            SelectedTeamCreatedViewModel fixtureTeam = new SelectedTeamCreatedViewModel();
            fixtureTeam.SelectedFixture = fixtureRepository.GetFixture(Int32.Parse(fixtureId[0]));

            List<ClubFixturePlayer> players = new List<ClubFixturePlayer>();

            int j = 0;
            int k = 0;

            for (int i = 0; i < playerId.Length; i++)
            {
                int thisFixtureId = Int32.Parse(fixtureId[0]);
                int thisPlayerId = Int32.Parse(playerId[i]);

                ClubFixturePlayer player = db.ClubFixturePlayers
                                             .Where(cfp => cfp.fixture_id == thisFixtureId
                                             && cfp.player_id == thisPlayerId).Single();

                if (bool.Parse(contact[j]) == true)
                {
                    player.contacted = bool.Parse(contact[j]);
                    j += 2;
                }
                else if (bool.Parse(contact[j]) == false)
                {
                    //player.contacted = bool.Parse(contact[j]);
                    j += 1;
                }

                if (bool.Parse(confirmed[k]) == true)
                {
                    player.confirmed = bool.Parse(confirmed[k]);
                    k += 2;
                }

                else if (bool.Parse(confirmed[k]) == false)
                {
                    //player.confirmed = bool.Parse(confirmed[k]);
                    k += 1;
                }
                //db.ClubFixturePlayers.Attach(player);
                db.ObjectStateManager.ChangeObjectState(player, EntityState.Modified);
                db.SaveChanges();
                players.Add(player);
            }

            fixtureTeam.TeamCreated = players;

            return fixtureTeam;
        }
    }
}